package com.gzc.just.play.last.war.common.scanner;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.common.handler.VirtualThreadServerFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息处理器扫描器
 * 自动扫描带有@MessageHandler注解的类并注册到框架中
 */
@Component
public class MessageHandlerScanner {
    private static final Logger logger = LoggerFactory.getLogger(MessageHandlerScanner.class);
    
    @Autowired
    private ApplicationContext applicationContext;
    
    /**
     * 服务器类型到MessageHandler.ServerType的映射
     */
    private static final Map<VirtualThreadServerFramework.ServerType, MessageHandler.ServerType> SERVER_TYPE_MAP = new HashMap<>();
    
    static {
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.GATE_SERVER, MessageHandler.ServerType.GATE_SERVER);
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.LOGIN_SERVER, MessageHandler.ServerType.LOGIN_SERVER);
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.BALANCE_SERVER, MessageHandler.ServerType.BALANCE_SERVER);
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.CENTRAL_SERVER, MessageHandler.ServerType.CENTRAL_SERVER);
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.SCENE_SERVER, MessageHandler.ServerType.SCENE_SERVER);
        SERVER_TYPE_MAP.put(VirtualThreadServerFramework.ServerType.ROBOT_CLIENT, MessageHandler.ServerType.ROBOT_CLIENT);
    }
    
    @PostConstruct
    public void scanAndRegister() {
        logger.info("Starting message handler scanning...");
        
        // 尝试获取所有可能的处理器类型
        Collection<SimpleMessageHandler> handlers = null;
        try {
            // 尝试获取接口类型的SimpleMessageHandler
            handlers = applicationContext.getBeansOfType(SimpleMessageHandler.class).values();
        } catch (Exception e) {
            logger.debug("Could not find interface SimpleMessageHandler beans, trying alternative approach", e);
            // 如果失败，说明没有找到接口类型的处理器，改为查找泛型处理器
            try {
                Map<String, com.gzc.just.play.last.war.common.message.MessageHandler<?>> genericHandlerMap = 
                    (Map<String, com.gzc.just.play.last.war.common.message.MessageHandler<?>>) 
                    (Map<?, ?>) applicationContext.getBeansOfType(com.gzc.just.play.last.war.common.message.MessageHandler.class);
                Collection<com.gzc.just.play.last.war.common.message.MessageHandler<?>> genericHandlers = 
                    genericHandlerMap.values();
                
                Map<MessageHandler.ServerType, Map<String, Object>> handlersByServerType = new HashMap<>();
                
                // 按服务器类型分组
                for (com.gzc.just.play.last.war.common.message.MessageHandler<?> handler : genericHandlers) {
                    MessageHandler annotation = handler.getClass().getAnnotation(MessageHandler.class);
                    if (annotation != null) {
                        MessageHandler.ServerType[] serverTypes = annotation.serverTypes();
                        
                        // 如果没有指定服务器类型，则适用于所有服务器类型
                        if (serverTypes.length == 0) {
                            serverTypes = MessageHandler.ServerType.values();
                        }
                        
                        for (MessageHandler.ServerType serverType : serverTypes) {
                            handlersByServerType.computeIfAbsent(serverType, k -> new HashMap<>())
                                .put(handler.getName(), handler);
                        }
                    }
                }
                
                // 存储扫描结果供后续使用
                this.handlersByServerType = handlersByServerType;
                
                // 打印扫描结果
                for (Map.Entry<MessageHandler.ServerType, Map<String, Object>> entry : handlersByServerType.entrySet()) {
                    logger.info("Found {} handlers for server type: {}", entry.getValue().size(), entry.getKey());
                }
                
                return; // 成功完成，退出方法
            } catch (Exception e2) {
                logger.warn("Could not find any message handlers", e2);
                // 初始化空映射
                this.handlersByServerType = new HashMap<>();
                return;
            }
        }
        
        Map<MessageHandler.ServerType, Map<String, Object>> handlersByServerType = new HashMap<>();
        
        // 按服务器类型分组
        for (SimpleMessageHandler handler : handlers) {
            MessageHandler annotation = handler.getClass().getAnnotation(MessageHandler.class);
            if (annotation != null) {
                MessageHandler.ServerType[] serverTypes = annotation.serverTypes();
                
                // 如果没有指定服务器类型，则适用于所有服务器类型
                if (serverTypes.length == 0) {
                    serverTypes = MessageHandler.ServerType.values();
                }
                
                for (MessageHandler.ServerType serverType : serverTypes) {
                    handlersByServerType.computeIfAbsent(serverType, k -> new HashMap<>())
                        .put(handler.getName(), handler);
                }
            }
        }
        
        // 打印扫描结果
        for (Map.Entry<MessageHandler.ServerType, Map<String, Object>> entry : handlersByServerType.entrySet()) {
            logger.info("Found {} handlers for server type: {}", entry.getValue().size(), entry.getKey());
        }
        
        // 存储扫描结果供后续使用
        this.handlersByServerType = handlersByServerType;
    }
    
    private Map<MessageHandler.ServerType, Map<String, Object>> handlersByServerType;
    
    /**
     * 获取适用于指定服务器类型的处理器
     * @param serverType 服务器类型
     * @return 处理器映射表
     */
    public Map<String, Object> getHandlersForServerType(VirtualThreadServerFramework.ServerType serverType) {
        MessageHandler.ServerType mappedType = SERVER_TYPE_MAP.get(serverType);
        if (mappedType == null) {
            logger.warn("Unknown server type: {}", serverType);
            return new HashMap<>();
        }
        
        Map<String, Object> handlers = handlersByServerType.get(mappedType);
        return handlers != null ? handlers : new HashMap<>();
    }
    
    /**
     * 注册适用于指定服务器类型的处理器到框架
     * @param serverType 服务器类型
     * @param framework 框架实例
     */
    @SuppressWarnings("unchecked")
    public void registerHandlersForServerType(VirtualThreadServerFramework.ServerType serverType, 
                                            VirtualThreadServerFramework framework) {
        Map<String, Object> handlers = getHandlersForServerType(serverType);
        
        for (Object handlerObj : handlers.values()) {
            // 尝试将处理器转换为接口类型
            if (handlerObj instanceof SimpleMessageHandler) {
                SimpleMessageHandler handler = (SimpleMessageHandler) handlerObj;
                framework.registerHandler(handler);
                logger.debug("Registered handler: {} for server type: {}", handler.getName(), serverType.getName());
            } else if (handlerObj instanceof com.gzc.just.play.last.war.common.message.MessageHandler) {
                // 如果是泛型类型，需要适配
                com.gzc.just.play.last.war.common.message.MessageHandler<?> handler = 
                    (com.gzc.just.play.last.war.common.message.MessageHandler<?>) handlerObj;
                framework.registerHandler(handler);
                logger.debug("Registered generic handler: {} for server type: {}", handler.getName(), serverType.getName());
            }
        }
        
        logger.info("Registered {} handlers for server type: {}", handlers.size(), serverType.getName());
    }
}